package utils

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// SetupLogger 初始化并返回一个配置好的日志记录器
func SetupLogger() *logrus.Logger {
	log := logrus.New()
	log.Out = os.Stdout
	log.SetFormatter(&logrus.JSONFormatter{})
	return log
}

// LoggerMiddleware 创建一个 Gin 中间件，用于记录请求日志
func LoggerMiddleware(log *logrus.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 读取请求参数
		var requestBody []byte
		if c.Request.Body != nil {
			requestBody, err := io.ReadAll(c.Request.Body)
			if err != nil {
				log.WithField("error", err.Error()).Error("Failed to read request body")
				c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
				return
			}
			c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
		}

		// 处理请求
		c.Next()

		// 记录返回参数
		responseData, exists := c.Get("response_data")
		var responseDataMap map[string]interface{}
		if exists {
			responseDataMap = responseData.(map[string]interface{})
		}

		// 记录日志
		log.WithFields(logrus.Fields{
			"status":        c.Writer.Status(),
			"method":        c.Request.Method,
			"path":          c.Request.URL.Path,
			"ip":            c.ClientIP(),
			"latency":       c.Writer.Header().Get("X-Response-Time"),
			"request_data":  parseJSON(requestBody),
			"response_data": responseDataMap,
		}).Info()
	}
}

// parseJSON 解析 JSON 数据并返回一个 map
func parseJSON(data []byte) map[string]interface{} {
	var result map[string]interface{}
	err := json.Unmarshal(data, &result)
	if err != nil {
		return nil
	}
	return result
}
